package com.wenjiang.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.wenjiang.common.constat.RedisKey;
import com.wenjiang.common.lang.Result;
import com.wenjiang.common.vo.CartGoodVo;
import com.wenjiang.common.vo.GoodInfo;
import com.wenjiang.service.MallCartService;
import com.wenjiang.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MallCartServiceImpl implements MallCartService {

    @Autowired
    RedisUtils redisUtils;
    @Override
    public Result addGoodToCart(String userId,String mallGooId) {

        //存入redis
        redisUtils.hset(RedisKey.mallCartKey+userId,mallGooId,1);

        return Result.succ("添加购物车成功");
    }

    @Override
    public void delGood(String userId, String mallGoodId) {
        //删除购物车某件商品
        redisUtils.hdel(RedisKey.mallCartKey+userId,mallGoodId);
    }

    public MallCartServiceImpl() {
        super();
    }

    @Override
    public void addGoodCount(String userId, String mallGoodId) {
           //购买数量+1
        redisUtils.hincr(RedisKey.mallCartKey+userId,mallGoodId,1);
    }
    @Override
    public void subGoodCount(String userId, String mallGoodId) {
        //购买数量-1
        redisUtils.hdecr(RedisKey.mallCartKey+userId,mallGoodId,1);
    }



    @Override
    public Result getMallUserCart(String userId) {

        List<CartGoodVo> cartGoodVos= new ArrayList<>();

        //获取redisKey
        Map<Object, Object> cartList = redisUtils.hmget(RedisKey.mallCartKey + userId);



        //遍历map

        for(Map.Entry<Object,Object> item:cartList.entrySet()){
            Object key = item.getKey();
            Integer value = (Integer)item.getValue();

            GoodInfo goodInfo = (GoodInfo)redisUtils.get(RedisKey.mallGoodKey+key.toString());

            CartGoodVo cartGoodVo = new CartGoodVo();

            BeanUtil.copyProperties(goodInfo,cartGoodVo);

            cartGoodVo.setCount(value);

            cartGoodVos.add(cartGoodVo);

        }

        return Result.succ(cartGoodVos);
    }
}
